package org.mespilus.mespilusweb.datalayer.usermanagement;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import org.mespilus.mespilusweb.datalayer.PMF;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;


@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Basket {
	@PrimaryKey
	@Persistent
	protected Key keyBasket;
	
	@Persistent
	protected int basketId;
	
	@Persistent
	protected List<Key> belongsToMember;
	
	@Persistent
	protected Key memberDealer;

	public Basket() {
		int size = getBaskets().size();
		keyBasket = KeyFactory.createKey(Basket.class.getSimpleName(), "_"+size);
		basketId = size;
	}

	public List<Key> getBelongsTo() {
		return belongsToMember;
	}

	public void setBelongsTo(List<Key> belongsTo) {
		this.belongsToMember = belongsTo;
	}

	public Key getDealer() {
		return memberDealer;
	}

	public void setDealer(Key dealer) {
		this.memberDealer = dealer;
	}
	
	public void addPerson(Key person) {
		belongsToMember.add(person);
	}
	
	public void delPerson(int index) {
		belongsToMember.remove(index);
	}
	
	public static void insert(Basket basket){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Transaction tx = pm.currentTransaction();
		try {
			tx.begin();
			pm.makePersistent(basket);
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pm.close();
		}
	}

	public static List<Basket> getBaskets(){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Basket.class);
		List<Basket> entries = (List<Basket>) query.execute();
		return entries;
	}
	
}
